package cn.codesea.housework_user.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.codesea.housework_user.R;
import cn.codesea.housework_user.adapter.JHListRcvAdapter;
import cn.codesea.housework_user.adapter.listener.OnCheckClickListener;
import cn.codesea.housework_user.adapter.listener.OnRecyclerItemClickUserListener;
import cn.codesea.housework_user.entity.Activity;
import cn.codesea.housework_user.entity.Order;
import cn.codesea.housework_user.entity.User;
import cn.codesea.housework_user.net.ServiceGenerator;
import cn.codesea.housework_user.net.data.Result;
import cn.codesea.housework_user.net.service.ActivityService;
import cn.codesea.housework_user.net.service.OrderService;
import cn.codesea.housework_user.net.service.UserService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 监护列表
 */
public class JHListActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    JHListRcvAdapter adapter;
    List<User> olders = new ArrayList<>();
    LinearLayoutManager mLinearLayoutManager;
    @BindView(R.id.confirm_tv)
    TextView confirm_tv;

    Order order;
    int userid;
    Activity act;


    List<Integer> olderIds = new ArrayList<>();

    String type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jhlist);
        ButterKnife.bind(this);
        init();
    }

    @OnClick(R.id.confirm_tv)
    public void confirm_tv(){

        if (olderIds.size() == 0){
            Toast.makeText(JHListActivity.this,"请选择老人！",Toast.LENGTH_SHORT).show();
            return;
        }

        if ("1".equals(type)){

            // 老人
            ActivityService activityService = ServiceGenerator.createService(ActivityService.class);
            Call<Result> call = activityService.joinActs(act.getActivityid(),userid);
            call.enqueue(new Callback<Result>(){
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    resultProcess(response.body(),"报名");
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {

                }
            });

        }else {
            order.setOlderid(olderIds.get(0));

            OrderService service = ServiceGenerator.createService(OrderService.class);
            Call<Result> call = service.order(order);
            call.enqueue(new Callback<Result>(){
                @Override
                public void onResponse(Call<Result> call, Response<Result> response) {
                    orderResult(response.body());
                }

                @Override
                public void onFailure(Call<Result> call, Throwable t) {
                    Toast.makeText(JHListActivity.this,"网络错误!",Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    /**
     * 结果处理
     */
    public void orderResult(Result result){
        if (result.getState() == 200){

            Dialog dialog = new AlertDialog.Builder(JHListActivity.this)
                    .setTitle("提示")
                    .setMessage( "下单成功！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(JHListActivity.this,MainActivity.class));
                            finish();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();

        }else {
            Toast.makeText(JHListActivity.this,"下单错误！",Toast.LENGTH_SHORT).show();
        }
    }

    private void init(){
        initData();
        initView();
    }

    private void initData() {
        Intent data = getIntent();
        order = (Order)data.getSerializableExtra("order");
        userid = data.getIntExtra("userid",-1);
        type = data.getStringExtra("type");
        act = (Activity) data.getSerializableExtra("act");
        loadData();
    }

    private void initView(){

        // 初始化 toolbar
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        adapter = new JHListRcvAdapter(this,olders);
        adapter.setRecyclerItemClickListener(new OnRecyclerItemClickUserListener() {
            @Override
            public void onItemClick(int Position, List<User> list) {

            }
        });
        adapter.setOnCheckClickListener(new OnCheckClickListener() {
            @Override
            public void OnCheckClick(int position, boolean isChecked) {
                Integer olderid = olders.get(position).getUserid();
                if (isChecked){
                    olderIds.add(olderid);
                }else {
                    olderIds.remove(olderid);
                }
            }
        });
        mLinearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        mRecyclerView.setLayoutManager(mLinearLayoutManager);
        mRecyclerView.setAdapter(adapter);
    }

    /**
     * 加载数据
     */
    private void loadData(){
        UserService userService = ServiceGenerator.createService(UserService.class);
        Call<Result> call = userService.getOlder(userid);
        call.enqueue(new Callback<Result>(){
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                resultProcess(response.body());
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });
    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result,String msg){
        if (result.getState() == 200){
            Dialog dialog = new AlertDialog.Builder(JHListActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "成功！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            startActivity(new Intent(JHListActivity.this,MainActivity.class));
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }else {
            Dialog dialog = new AlertDialog.Builder(JHListActivity.this)
                    .setTitle("提示")
                    .setMessage(msg + "失败！")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    })
                    .create();
            dialog.setCancelable(false);
            dialog.show();
        }
    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result){
        Type type = new TypeToken<List<User>>(){}.getType();
        olders.clear();
        olders.addAll((List<User>)new Gson().fromJson(String.valueOf(result.getRes()),type));
        adapter.notifyDataSetChanged();

        if (olders.size() == 0){
            Toast.makeText(JHListActivity.this,"无监管老人！",Toast.LENGTH_LONG).show();
        }
    }

}
